const ip = "127.0.0.1"
const port = "6163"
const projection = ol.proj.get("EPSG:4326")
const siteConfig = {
    ip: ip,
    port: port
}
const wuhan = {
    name: "WUHAN",
    center: [114.33, 30.6],
    zoom: 12
}
const place = wuhan
const extent = [place.center[0] - 0.03, 30.5, place.center[0] + 0.03, 30.7]

/**
 * @type {ol.Map}
 */
var map
/**
 * 天地图图层
 * @type {Zondy.Map.TianDiTu}
 */
var tiandituLayer = new Zondy.Map.TianDiTu({
    layerType: Zondy.Enum.Map.TiandituType.VEC_IGS,
    projection: projection,
    ip: "develop.smaryun.com",
    port: "6163",
})
var tiandituLayer2 = new Zondy.Map.TianDiTu({
    layerType: Zondy.Enum.Map.TiandituType.CIA_IGS,
    projection: projection,
    ip: "develop.smaryun.com",
    port: "6163",
})
/**
 *
 * @type {ol.layer.Layer[]}
 */
var mapLayers = [tiandituLayer, tiandituLayer2]

/**
 * MapGIS 地图的图层
 * @type {Zondy.Map.Layer[]}
 */
var viewLayers = []
/**
 * 请求结果返回对应的类型。类型声明见 ts/SingleLayerInfo.ts
 * @type {SingleLayerInfo[]}
 */
var resultLayers = []
/**
 * 每个图层对应是否可见
 * @type {boolean[]}
 */
var visibleLayers = []
/**
 * 图层名称，用于右侧显示。
 * @type {string[]}
 */
var layerNames = []
/**
 *
 * @type {ol.control.ScaleLine}
 */
var scaleLineControl = new ol.control.ScaleLine({units: "metric"})
/**
 * 鼠标对应的坐标位置。缩放级数，经度，纬度
 * @type {ol.control.MousePosition}
 */
var mousePositionControl = new ol.control.MousePosition({
    coordinateFormat: (coordinate) => {
        return map.getView().getZoom() + "\t" + ol.coordinate.format(coordinate, "{y}, {x}", 4)
    },
    projection: projection,
    className: "this-mouse-position",
    target: document.getElementById("mouse-position"),
    undefinedHTML: "&nbsp;"
})

function init() {
    (function () {
        let docCatalog = new Zondy.Service.Catalog.MapDoc({
            projection: projection,
            ip: ip,
            port: port,
            docName: place.name,
            mapIndex: 0,
        })
        docCatalog.getLayersInfo(getLayersListSuccess)
    })()

    /**
     * 获取所有的层的信息
     * @param {[SingleLayerInfo]} result
     */
    function getLayersListSuccess(result) {
        getUsername()
        resultLayers = result
        viewLayers = result.map((it) => {
            return new Zondy.Map.Layer("MapGIS IGS VectorLayer", [it.URL], {
                ip: ip,
                port: port,
                isBaseLayer: true,
                opacity: 0.6
            })
        })
        viewLayers.forEach((it) => {
            it.setVisible(false)
            mapLayers.push(it)
        })
        map = new ol.Map({
            target: "mapCon",
            layers: mapLayers,
            view: new ol.View({
                center: place.center,
                projection: projection,
                zoom: place.zoom
            }),
            controls: ol.control.defaults().extend([
                new ol.control.Attribution(),
                mousePositionControl,
                new ol.control.ZoomSlider(),
                new ol.control.ZoomToExtent({
                    extent: extent
                }),
                new ol.control.FullScreen(),
                scaleLineControl,
            ])
        })
        loadLayerTreeControl(map, "layerTree")
        bindUIListeners()
    }
}


/**
 *
 * @param {SingleLayerInfo[]} results
 * @param {number} layerNumber
 * @param {string} inputName
 * @param {*} cb callback 回调函数
 */
function queryService(results, layerNumber, inputName, cb) {
    let queryStruct = new Zondy.Service.QueryFeatureStruct()
    queryStruct.IncludeGeometry = true
    let queryParam = new Zondy.Service.QueryByLayerParameter(results[layerNumber].URL, {
        resultFormat: "json",
        struct: queryStruct,
    })
    // 设置查询分页号
    queryParam.pageIndex = 0
    // 设置查询要素数目
    queryParam.recordNumber = 0
    let queryService = new Zondy.Service.QueryDocFeature(queryParam, place.name, layerNumber, siteConfig)
    queryService.query(
        /**
         *
         * @param {Zondy.Object.FeatureSet} res
         */
        res => {
            let name = res.AttStruct.FldName[1]
            queryParam.recordNumber = 20
            queryParam.where = `${name} like '%${inputName}%'`
            let queryService = new Zondy.Service.QueryDocFeature(queryParam, place.name, layerNumber, siteConfig)
            queryService.query(ss => {
                cb(ss)
            })
        }, err => {
            console.log("err")
            console.log(err)
        }
    )
}

/**
 *
 * @param {ol.source.Vector} featureSource
 */
function removeAllFeatures(featureSource) {
    if (featureSource) {
        featureSource.getFeatures().forEach(it => {
            featureSource.removeFeature(it)
        })
    }
}

const removeAllOverlays = () => {
    const repeat = (f, n) => {
        for (let i = 0; i < n; i++) f()
    }

    repeat(() => {
        map.getOverlays().forEach(it => {
            map.removeOverlay(it)
        })
    }, 5)
}

function removeInteractions() {
    if (measureDrawInteration)
        map.removeInteraction(measureDrawInteration)
    if (queryDrawInteraction)
        map.removeInteraction(queryDrawInteraction)
}

function removeDrawLayers() {
    if (measureVector)
        map.removeLayer(measureVector)
    if (queryVector)
        map.removeLayer(queryVector)

    if (queryDrawLayer)
        map.removeLayer(queryDrawLayer)
}

const removeOthers = () => {
    currentType = Zondy.Enum.FeatureType.Unknown
    removeAllOverlays()
    removeInteractions()
    removeDrawLayers()
    removeAllFeatures(querySource)
    removeAllFeatures(measureSource)
}

const getLayerTable = (layerObj) => {
    let box = $(layerObj).find(".layui-layer-content")
        .find(".layui-form")
        .find(".layui-table-box")
    let header = box.find(".layui-table-header").find('table').find('thead').find('tr').find('th')
    let tds = box.find(".layui-table-body").find('table').find('tbody').find('tr').find('td')
    return {headers: header, tds: tds}
}

const useAdmin = ()=>{
    $("#editItem").removeClass("layui-hide")
    $("#saveItem").removeClass("layui-hide")
}